import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:intl/intl.dart';
import '../models/transaction.dart';
import '../services/database_service.dart';
import 'dart:math';
import '../pages/yearly_statistics_page.dart';

class StatisticsPage extends StatefulWidget {
  const StatisticsPage({super.key});

  @override
  State<StatisticsPage> createState() => _StatisticsPageState();
}

class _StatisticsPageState extends State<StatisticsPage> {
  final _numberFormat = NumberFormat('#,##0.00');
  DateTime _selectedMonth = DateTime.now();
  late Future<List<Transaction>> _transactionsFuture;
  int? _touchedPieIndex;
  bool _showAllCategories = true;
  final Map<String, bool> _visibleCategories = {};

  @override
  void initState() {
    super.initState();
    _loadTransactions();
  }

  void _loadTransactions() {
    _transactionsFuture = DatabaseService.instance.getTransactionsByMonth(_selectedMonth);
  }

  Future<void> _selectMonth() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedMonth,
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
      initialEntryMode: DatePickerEntryMode.calendarOnly,
    );
    
    if (picked != null) {
      setState(() {
        _selectedMonth = DateTime(picked.year, picked.month);
        _loadTransactions();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: FutureBuilder<List<Transaction>>(
        future: _transactionsFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (snapshot.hasError) {
            return Center(child: Text('错误: ${snapshot.error}'));
          }

          final transactions = snapshot.data ?? [];
          final stats = _calculateStats(transactions);

          return CustomScrollView(
            slivers: [
              SliverAppBar(
                floating: true,
                pinned: true,
                title: GestureDetector(
                  onTap: _selectMonth,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        '${_selectedMonth.year}年${_selectedMonth.month}月',
                      ),
                      const Icon(Icons.arrow_drop_down),
                    ],
                  ),
                ),
                actions: [
                  IconButton(
                    icon: const Icon(Icons.calendar_today),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => YearlyStatisticsPage(
                            initialYear: _selectedMonth.year,
                          ),
                        ),
                      );
                    },
                  ),
                ],
                bottom: const TabBar(
                  tabs: [
                    Tab(text: '概览'),
                    Tab(text: '分类'),
                    Tab(text: '趋势'),
                  ],
                ),
              ),
              SliverFillRemaining(
                child: TabBarView(
                  children: [
                    _buildOverviewTab(stats),
                    _buildCategoryTab(stats),
                    _buildTrendTab(stats),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildOverviewTab(StatisticsData stats) {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    _buildStatItem('收入', stats.totalIncome, Colors.green),
                    _buildStatItem('支出', stats.totalExpense, Colors.red),
                  ],
                ),
                const Divider(height: 32),
                _buildStatItem(
                  '结余',
                  stats.totalIncome - stats.totalExpense,
                  Colors.blue,
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),
        AspectRatio(
          aspectRatio: 1.5,
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: BarChart(
                BarChartData(
                  alignment: BarChartAlignment.spaceAround,
                  maxY: max(stats.totalIncome, stats.totalExpense) * 1.2,
                  titlesData: FlTitlesData(
                    show: true,
                    topTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    rightTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    bottomTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        getTitlesWidget: (value, meta) {
                          switch (value.toInt()) {
                            case 0:
                              return const Text('收入');
                            case 1:
                              return const Text('支出');
                            default:
                              return const Text('');
                          }
                        },
                      ),
                    ),
                  ),
                  gridData: const FlGridData(show: false),
                  borderData: FlBorderData(show: false),
                  barGroups: [
                    BarChartGroupData(
                      x: 0,
                      barRods: [
                        BarChartRodData(
                          toY: stats.totalIncome,
                          color: Colors.green,
                          width: 40,
                          borderRadius: BorderRadius.circular(4),
                          backDrawRodData: BackgroundBarChartRodData(
                            show: true,
                            toY: max(stats.totalIncome, stats.totalExpense) * 1.2,
                            color: Colors.grey.withOpacity(0.1),
                          ),
                        ),
                      ],
                    ),
                    BarChartGroupData(
                      x: 1,
                      barRods: [
                        BarChartRodData(
                          toY: stats.totalExpense,
                          color: Colors.red,
                          width: 40,
                          borderRadius: BorderRadius.circular(4),
                          backDrawRodData: BackgroundBarChartRodData(
                            show: true,
                            toY: max(stats.totalIncome, stats.totalExpense) * 1.2,
                            color: Colors.grey.withOpacity(0.1),
                          ),
                        ),
                      ],
                    ),
                  ],
                  barTouchData: BarTouchData(
                    enabled: true,
                    touchTooltipData: BarTouchTooltipData(
                      tooltipBgColor: Colors.black87,
                      getTooltipItem: (group, groupIndex, rod, rodIndex) {
                        String title = groupIndex == 0 ? '收入' : '支出';
                        double amount = groupIndex == 0 ? stats.totalIncome : stats.totalExpense;
                        return BarTooltipItem(
                          '$title\n¥${_numberFormat.format(amount)}',
                          const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        );
                      },
                    ),
                  ),
                ),
                swapAnimationDuration: const Duration(milliseconds: 250),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildCategoryTab(StatisticsData stats) {
    if (stats.expenseByCategory.isEmpty) {
      return const Center(child: Text('暂无数据'));
    }

    // 初始化可见性状态
    stats.expenseByCategory.forEach((key, value) {
      _visibleCategories[key] ??= true;
    });

    final visibleData = Map.fromEntries(
      stats.expenseByCategory.entries.where((e) => _visibleCategories[e.key] ?? true),
    );

    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            TextButton.icon(
              icon: Icon(_showAllCategories ? Icons.visibility_off : Icons.visibility),
              label: Text(_showAllCategories ? '隐藏全部' : '显示全部'),
              onPressed: () {
                setState(() {
                  _showAllCategories = !_showAllCategories;
                  stats.expenseByCategory.keys.forEach((key) {
                    _visibleCategories[key] = _showAllCategories;
                  });
                });
              },
            ),
          ],
        ),
        AspectRatio(
          aspectRatio: 1,
          child: PieChart(
            PieChartData(
              sections: _buildPieChartSections(visibleData),
              sectionsSpace: 2,
              centerSpaceRadius: 40,
              pieTouchData: PieTouchData(
                touchCallback: (FlTouchEvent event, pieTouchResponse) {
                  setState(() {
                    if (!event.isInterestedForInteractions ||
                        pieTouchResponse == null ||
                        pieTouchResponse.touchedSection == null) {
                      _touchedPieIndex = -1;
                      return;
                    }
                    _touchedPieIndex = pieTouchResponse.touchedSection!.touchedSectionIndex;
                  });
                },
              ),
            ),
            swapAnimationDuration: const Duration(milliseconds: 250),
          ),
        ),
        const SizedBox(height: 16),
        Card(
          child: Column(
            children: _buildInteractiveCategoryList(stats.expenseByCategory),
          ),
        ),
      ],
    );
  }

  List<Widget> _buildInteractiveCategoryList(Map<String, double> data) {
    final sortedEntries = data.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));
    final total = data.values.reduce((a, b) => a + b);

    return sortedEntries.map((entry) {
      final percentage = (entry.value / total * 100).toStringAsFixed(1);
      final isVisible = _visibleCategories[entry.key] ?? true;
      
      return ListTile(
        leading: IconButton(
          icon: Icon(
            isVisible ? Icons.visibility : Icons.visibility_off,
            color: isVisible ? Colors.blue : Colors.grey,
          ),
          onPressed: () {
            setState(() {
              _visibleCategories[entry.key] = !isVisible;
              _showAllCategories = _visibleCategories.values.every((v) => v);
            });
          },
        ),
        title: Text(entry.key),
        subtitle: LinearProgressIndicator(
          value: entry.value / total,
          backgroundColor: Colors.grey[200],
          valueColor: AlwaysStoppedAnimation<Color>(
            _getColorForCategory(entry.key, data.keys.toList()),
          ),
        ),
        trailing: Text(
          '¥${_numberFormat.format(entry.value)}\n$percentage%',
          textAlign: TextAlign.end,
        ),
      );
    }).toList();
  }

  Widget _buildTrendTab(StatisticsData stats) {
    if (stats.expenseByDay.isEmpty) {
      return const Center(child: Text('暂无数据'));
    }

    final dailyData = stats.expenseByDay.entries.toList()
      ..sort((a, b) => a.key.compareTo(b.key));

    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        AspectRatio(
          aspectRatio: 1.5,
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: LineChart(
                LineChartData(
                  gridData: const FlGridData(show: false),
                  titlesData: FlTitlesData(
                    leftTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    rightTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    topTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    bottomTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        getTitlesWidget: (value, meta) {
                          if (value % 5 != 0) return const Text('');
                          return Text(value.toInt().toString());
                        },
                      ),
                    ),
                  ),
                  borderData: FlBorderData(show: false),
                  lineBarsData: [
                    LineChartBarData(
                      spots: dailyData
                          .map((e) => FlSpot(e.key.toDouble(), e.value))
                          .toList(),
                      isCurved: true,
                      color: Colors.blue,
                      barWidth: 2,
                      dotData: const FlDotData(show: false),
                      belowBarData: BarAreaData(
                        show: true,
                        color: Colors.blue.withOpacity(0.1),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildDailyExpenseList(dailyData),
      ],
    );
  }

  Widget _buildDailyExpenseList(List<MapEntry<int, double>> dailyData) {
    return Card(
      child: Column(
        children: dailyData.reversed
            .where((entry) => entry.value > 0)
            .map((entry) => ListTile(
                  title: Text('${entry.key}日'),
                  trailing: Text(
                    '¥${_numberFormat.format(entry.value)}',
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ))
            .toList(),
      ),
    );
  }

  Widget _buildStatItem(String label, double amount, Color color) {
    return Column(
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          '¥${_numberFormat.format(amount)}',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  List<PieChartSectionData> _buildPieChartSections(Map<String, double> data) {
    final total = data.values.reduce((a, b) => a + b);
    final categories = data.keys.toList();

    return data.entries.map((entry) {
      final index = categories.indexOf(entry.key);
      final percentage = (entry.value / total * 100).toStringAsFixed(1);
      final isTouched = index == _touchedPieIndex;
      final radius = isTouched ? 110.0 : 100.0;
      final fontSize = isTouched ? 14.0 : 12.0;
      
      return PieChartSectionData(
        color: _getColorForCategory(entry.key, categories),
        value: entry.value,
        title: '$percentage%',
        radius: radius,
        titleStyle: TextStyle(
          fontSize: fontSize,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      );
    }).toList();
  }

  Color _getColorForCategory(String category, List<String> categories) {
    final colors = [
      Colors.red,
      Colors.blue,
      Colors.green,
      Colors.orange,
      Colors.purple,
      Colors.teal,
      Colors.pink,
      Colors.indigo,
      Colors.amber,
      Colors.cyan,
    ];
    final index = categories.indexOf(category);
    return colors[index % colors.length];
  }

  StatisticsData _calculateStats(List<Transaction> transactions) {
    var totalIncome = 0.0;
    var totalExpense = 0.0;
    final expenseByCategory = <String, double>{};
    final expenseByDay = <int, double>{};

    // 初始化每日支出数据
    for (var i = 1; i <= 31; i++) {
      expenseByDay[i] = 0;
    }

    for (final transaction in transactions) {
      if (transaction.type == TransactionType.income) {
        totalIncome += transaction.amount;
      } else {
        totalExpense += transaction.amount;
        // 更新分类统计
        expenseByCategory[transaction.category] = 
            (expenseByCategory[transaction.category] ?? 0) + transaction.amount;
        // 更新每日支出
        expenseByDay[transaction.date.day] = 
            (expenseByDay[transaction.date.day] ?? 0) + transaction.amount;
      }
    }

    return StatisticsData(
      totalIncome: totalIncome,
      totalExpense: totalExpense,
      expenseByCategory: expenseByCategory,
      expenseByDay: expenseByDay,
    );
  }
}

class StatisticsData {
  final double totalIncome;
  final double totalExpense;
  final Map<String, double> expenseByCategory;
  final Map<int, double> expenseByDay;

  StatisticsData({
    required this.totalIncome,
    required this.totalExpense,
    required this.expenseByCategory,
    required this.expenseByDay,
  });
} 